package com.mitcub.panda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mitcub.panda.base.BaseQuery;
import com.mitcub.panda.base.BaseServiceImpl;
import com.mitcub.panda.entity.Menu;
import com.mitcub.panda.entity.Role;
import com.mitcub.panda.mapper.MenuMapper;
import com.mitcub.panda.mapper.RoleMapper;
import com.mitcub.panda.query.RoleQuery;
import com.mitcub.panda.service.IRoleService;
import com.mitcub.panda.utils.RespResult;
import com.mitcub.panda.vo.RoleMenuVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @项目名称: panda
 * @类名称: DeptServiceImpl
 * @类描述: 部门 服务实现类
 * @作者: tangloong
 * @创建时间: 2021/11/2 17:22
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private MenuMapper menuMapper;

    /**
     * 获取数据列表
     * @param query 查询条件
     * @return
     */
    @Override
    public RespResult getList(BaseQuery query) {
        RoleQuery depQuery = (RoleQuery) query;
        // 查询条件
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        // 部门名称
        if (!StringUtils.isEmpty(depQuery.getName())) {
            queryWrapper.like("name", depQuery.getName());
        }
        queryWrapper.eq("mark", 1);
        //queryWrapper.orderByDesc("id");

        // 查询数据
        Page<Role> page = new Page<>(depQuery.getPage(), depQuery.getLimit());
        IPage<Role> data = roleMapper.selectPage(page, queryWrapper);
        return RespResult.success("操作成功",  data.getRecords(), data.getTotal());
    }


    /**
     * 根据角色ID 获取权限
     * @param roleId    角色ID
     * @return
     */
    @Override
    public RespResult getRolePermissionByRoleId(Integer roleId) {
        List<Menu> menus = menuMapper.selectList(new QueryWrapper<Menu>().select("name","id","pid","status"));
        Role role = roleMapper.selectById(roleId);
        String[] auths = {};
        if(null != role){
            auths = role.getAuth().split(",");
        }
        Set<String> set = new HashSet<>(Arrays.asList(auths));
        List<RoleMenuVo> roleMenuVos = new ArrayList<>();
        menus.forEach(item -> {
            RoleMenuVo roleMenuVo = new RoleMenuVo();
            // 拷贝属性  属性必须一致 Integer和Long 不能拷贝
            BeanUtils.copyProperties(item, roleMenuVo);

            roleMenuVo.setOpen((item.getStatus()==1));
            roleMenuVo.setChecked(set.contains(item.getId()+""));
            roleMenuVos.add(roleMenuVo);
        });
       return RespResult.success(roleMenuVos);
    }

    @Override
    public RespResult setRolePermission(Role entity) {
        return super.edit(entity);
    }
}